<?php

namespace adminmatrix\plugins;

use think\facade\Config;
use think\Request;
use Closure;
use think\App;


enum Type  {
    case project;
}
class Middleware
{

    use TraitInitRoute;
    /**
     * @var App
     */
    protected  $app;

    protected string $pluginName = '';

    protected array $plugin_info      =   [];

    public function __construct(App $app)
    {
        $this->app = $app;
    }
    public function handle($request, Closure $next)
    {
        $path = $this->app->request->pathinfo();
        $path = explode("/" , trim($path , '/'));
        array_shift($path);

        $this->pluginName = $pluginName = array_shift($path);
        $controller =  array_shift($path) ?? 'Index' ; // 控制器名称
        $controller =   str_replace('.','/',$controller) ?? 'Index';
        $action     =   ucfirst(array_shift($path) ?? 'index'); //  方法名称
        $suffix = Config::get('route.controller_suffix', false) == true ? ucfirst(Config::get('route.controller_layer')) : '';

        // 处理 controller 为驼峰写法
        $controllerParts = explode('/', $controller);
        $lastPartIndex = count($controllerParts) - 1;
        $controllerParts[$lastPartIndex] = ucfirst($controllerParts[$lastPartIndex]);
        $controller = implode('/', $controllerParts);

        // 构建完整命名空间
        $className = "/plugins/{$pluginName}/controller/{$controller}{$suffix}";
        $className = str_replace("/" ,'\\' , $className);

        // 插件配置文件
        $info_file = $this->app->getRootPath() . 'plugins' . DS . $this->pluginName . DS . 'config.json';
        if (file_exists($info_file))
        {
            $json_content = file_get_contents( $info_file );
            $data = json_decode($json_content, true);
            $this->plugin_info  =  $request->plugin_info = $data;
        }


        return $next($request);
    }
}